import axios from 'axios'
import {Message, MessageBox} from 'element-ui'
import store from '@/store'
import {getToken} from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_BPM_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 30000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (getToken()) {
      config.headers['Authorization'] = getToken()
    }
    // if (store.getters.token) {
    //
    // }
    return config
  },
  error => {
    // do something with request error
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data

    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 0) {

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 99) {
        // to re-login
        MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return res
    } else {
      return res
    }
  },
  error => {
    if (error.response){
      var status = error.response.status
      if (status){
        if (status == 500) {
          if (error.response.data.code == 401) {
            MessageBox.confirm('登录信息已失效，您可以取消以停留在此页面，或者重新登录' , '确认', {
              confirmButtonText: '重新登录',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              store.dispatch('user/resetToken').then(() => {
                location.reload()
              })
              return Promise.reject(error)

            })

          }
        }
      }else{
        MessageBox.confirm('登录信息已失效，您可以取消以停留在此页面，或者重新登录' , '确认', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
          return Promise.reject(error)

        })
      }
    }else{
      Message({
        message: '系统升级中...',
        type: 'error',
        duration: 800
      })
      return Promise.reject(error)
    }


    // Message({
    //   message: '系统升级中...',
    //   type: 'error',
    //   duration: 800
    // })
    // return Promise.reject(error)
  }
)

export default service
